package freespiritsocial.io.user.util

import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
import freespiritsocial.io.user.data.model.bean.ContactsBean

class ContactsHelper (val context: Context) {

    //联系人提供者的uri
    private val phoneUri: Uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI

    //获取所有联系人
    val phone: ArrayList<ContactsBean>
        get() {
            val list: ArrayList<ContactsBean> = ArrayList()
            val cr: ContentResolver = context.contentResolver
            val cursor: Cursor? = cr.query(
                phoneUri,
                arrayOf(NUM, NAME),
                null,
                null,
                null
            )
            cursor?.let {
                while (it.moveToNext()) {
                    val phoneDto = ContactsBean(
                        it.getString(it.getColumnIndex(NAME)),
                        it.getString(it.getColumnIndex(NUM)).replace(" ","")
                    )
                    list.add(phoneDto)
                }
            }
            cursor?.close()
            return list
        }

    companion object {
        // 号码
        val NUM: String = ContactsContract.CommonDataKinds.Phone.NUMBER

        // 联系人姓名
        val NAME: String = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
    }

}